package com.keke.beauty.sys.file.controller;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.keke.beauty.sys.file.entity.TabFile;
import com.keke.beauty.sys.file.service.TabFileService;
import com.keke.beauty.sys.user.entity.SysUser;
import com.keke.beauty.utils.pojo.Result;
import com.keke.beauty.utils.tools.ResultUtil;

/**
 * 文件管理控制层
 *
 * @author
 * @Data 2019年02月22日 16:14:01
 */
@RestController
@RequestMapping("/file")
public class TabFileController {

    @Autowired
    private TabFileService service;

    @Value("${file.root-path}")
    private String rootPath;

    @Value("${file.http}")
    private String rootHttp;

    private final static String PREFIX_VIDEO="video/";

    /**
     * 上传文件
     *
     * @param file
     * @return
     * @author
     * @Data 2019年02月22日 16:14:01
     */
    @PostMapping
    public Result upload(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String contentType = file.getContentType();
        String fileTyle = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String newFileNmae = UUID.randomUUID() + "_" + new Date().getTime();
        String nowFileName =  newFileNmae+ fileTyle;
        String filePath = rootPath + File.separator + nowFileName;
        File toFile = new File(filePath);
        // 判断路径是否存在
        if (!toFile.getParentFile().exists()) {
            toFile.getParentFile().mkdirs();
        }

        try {
            file.transferTo(toFile);
            TabFile tabFile = new TabFile();
            tabFile.setFileName(nowFileName);
            tabFile.setType(file.getContentType());
            tabFile.setOldFileName(file.getOriginalFilename());
            tabFile.setFilePath(filePath);
            tabFile.setSize(String.valueOf(file.getSize()));
            tabFile.setCreateTime(new Date());
            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
            if (!StringUtils.isEmpty(user)) {
                tabFile.setCreater(user.getId());
            }
            if(!StringUtils.isEmpty(fileName)&&contentType.contains(PREFIX_VIDEO)){
                try {
                    String imgName = newFileNmae+".jpg";
                    tabFile.setImgName(imgName);
                    fetchFrame(filePath,rootPath + File.separator + imgName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            service.insert(tabFile);
            return ResultUtil.success(tabFile.getId());
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return ResultUtil.error("上传失败！");
        }
    }

    /**
     * 查看文件管理
     *
     * @param id
     * @return
     * @author
     * @Data 2019年02月22日 16:14:01
     */
    @GetMapping("/{id}")
    public void dowload(HttpServletResponse response, @PathVariable int id) {
        TabFile tabFile = service.findByPrimaryKey(id);
        try {
//            System.out.println(rootHttp + tabFile.getFileName());
            response.sendRedirect(rootHttp + tabFile.getFileName());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询文件
     *
     * @param id
     * @return
     * @author
     * @Data 2019年02月22日 16:14:01
     */
    @RequestMapping("getFile/{id}")
    public Result getFile(HttpServletResponse response, @PathVariable int id) {
        return ResultUtil.success(service.findByPrimaryKey(id));
    }

    /**
     * 根据名称获取文件
     *
     * @param name
     * @return
     * @author
     * @Data 2019年02月22日 16:14:01
     */
    @RequestMapping("dowloadByName/{name}")
    public void dowloadByName(HttpServletResponse response, @PathVariable String name) {
        try {
//            System.out.println(rootHttp + tabFile.getFileName());
            response.sendRedirect(rootHttp + name);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取预览图像
     * @param videofile
     * @param framefile
     * @throws Exception
     */
    private void fetchFrame(String videofile, String framefile) throws Exception {
        File targetFile = new File(framefile);
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdirs();
        }
        try{
            File file2 = new File(videofile);
            if (file2.exists()) {
                System.out.println("文件存在，路径正确！");
                FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file2);
                ff.start();
                int ftp = ff.getLengthInFrames();
                int flag=0;
                Frame frame = null;
                while (flag <= ftp) {
                    //获取帧
                    frame = ff.grabImage();
                    //过滤前3帧，避免出现全黑图片
                    if ((flag>3)&&(frame != null)) {
                        break;
                    }
                    flag++;
                }
                ImageIO.write(FrameToBufferedImage(frame), "jpg", targetFile);
                ff.close();
                ff.stop();
            }
        }catch(Exception e){
            System.out.println("获取预览图失败:"+e.getMessage());
        }
    }

    private RenderedImage FrameToBufferedImage(Frame frame) {
        //创建BufferedImage对象
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bufferedImage = converter.getBufferedImage(frame);
        return bufferedImage;
    }
}